package com.pcg.posgasstation.view;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.pcg.posgasstation.R;
import com.pcg.posgasstation.adapter.GoodsAdapter;
import com.pcg.posgasstation.base.BaseActivity;
import com.pcg.posgasstation.event.ExitLoginEvent;
import com.pcg.posgasstation.model.cache.CacheManager;
import com.pcg.posgasstation.model.network.ApiClient;
import com.pcg.posgasstation.model.network.entity.BaseEntity;
import com.pcg.posgasstation.model.network.entity.GoodsItemEntity;
import com.pcg.posgasstation.utils.LogUtil;
import com.pcg.posgasstation.utils.ToastUtils;
import com.pcg.posgasstation.view.widget.RcvGridItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    @BindView(R.id.ivMe)
    TextView mIvMe;
    //    @BindView(R.id.tvHistory)
//    TextView mTvHistory;
//    @BindView(R.id.tvAddMember)
//    TextView mTvAddMember;
    @BindView(R.id.rcvGoodsList)
    RecyclerView mRcvGoodsList;
    @BindView(R.id.swiperefresh)
    SwipeRefreshLayout mSwiperefresh;

    private static final String TAG = MainActivity.class.getSimpleName();
    private GoodsAdapter mAdapter;

    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        initViews();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.ivMe)
    void meClick() {
        PersonInfoActivity.startActivity(mContext);
    }

//    @OnClick(R.id.tvHistory)
//    void historyClick() {
//        OrderHistoryActivity.startActivity(mContext);
//    }
//
//    @OnClick(R.id.tvAddMember)
//    void addMemberClick() {
//        AddMemberActivity.startActivity(mContext);
//    }

    private void initViews() {
        mProgressDialog = new ProgressDialog(mContext);
        initRecyclerView();
        loadGoodsList();
        mSwiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadGoodsList();
            }
        });
    }

    private void setRefreshing(boolean refreshing) {
        mSwiperefresh.setRefreshing(refreshing);
    }

    private void initRecyclerView() {
        List<GoodsItemEntity> data = new ArrayList<>();

//        String cacheData = CacheManager.getInstance().getMemberListCache();
//        if (!TextUtils.isEmpty(cacheData)) {
//            List<MemberListItemEntity> cacheList = GsonHelper.getGson().fromJson(cacheData, new TypeToken<List<MemberListItemEntity>>() {
//            }.getType());
//            if (cacheList != null && !cacheList.isEmpty()) {
//                mMemberList.clear();
//                mMemberList.addAll(cacheList);
//                data.addAll(cacheList);
//            }
//        }

        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
        mAdapter = new GoodsAdapter(R.layout.item_main_goods, data);
        mRcvGoodsList.setLayoutManager(layoutManager);
        mRcvGoodsList.setAdapter(mAdapter);

        mAdapter.disableLoadMoreIfNotFullPage(mRcvGoodsList);
        mAdapter.setEnableLoadMore(false);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                final GoodsItemEntity clickItemData = (GoodsItemEntity) adapter.getItem(position);
                if (clickItemData == null) {
                    return;
                }
                startGoodDetailActivity(clickItemData);
            }
        });

        //TEST 第二种方案

        //添加Header对应的View
        View view = getLayoutInflater().inflate(R.layout.layout_main_header_view, (ViewGroup) mRcvGoodsList.getParent(), false);
        //添加Header对应的点击事件
        view.findViewById(R.id.tvHistory).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OrderHistoryActivity.startActivity(mContext);
            }
        });

        view.findViewById(R.id.tvAddMember).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddMemberActivity.startActivity(mContext);
            }
        });
        //调用BaseQuickAdapter
        mAdapter.addHeaderView(view);

        //TEST 第二种方案

        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
        mRcvGoodsList.addItemDecoration(new RcvGridItemDecoration(spacingInPixels));
    }

    private void loadGoodsList() {
        if (mProgressDialog != null) {
            mProgressDialog.show();
        }

        ApiClient.getApiService().getFoodList(ApiClient.getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity<List<GoodsItemEntity>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseEntity<List<GoodsItemEntity>> entity) {
                        LogUtil.e(TAG, "get good list onNext");
                        setRefreshing(false);
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }
                        if (entity != null && entity.isSuccess()) {
                            List<GoodsItemEntity> goodsList = entity.getData();
                            if (goodsList != null) {
                                refreshData(goodsList);
                            }
                        } else {
                            ToastUtils.showToast(entity.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.e(TAG, "get good list onError");
                        setRefreshing(false);
                        if (mProgressDialog != null) {
                            mProgressDialog.hide();
                        }
                        exitLogin();
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void refreshData(List<GoodsItemEntity> goodsList) {
        List<GoodsItemEntity> data = new ArrayList<>();
        data.addAll(goodsList);
        mAdapter.replaceData(data);
        mAdapter.loadMoreComplete();
    }

    private void startGoodDetailActivity(GoodsItemEntity entity) {
        MemberInfoActivity.startActivity(mContext, entity);
    }

    @Subscribe
    public void receiveLoginoutEvent(ExitLoginEvent event) {
        LogUtil.e(TAG, "receive exit Login Event");
        exitLogin();
    }

    private void exitLogin() {
        ApiClient.setToken("");
        CacheManager.getInstance().setLoginedToken("");

        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        mContext.startActivity(intent);
        finish();
    }

}
